package com.hson.demo.base.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * 获取法定节假日&周末
 * @author chenhs
 * @time 2015年8月15日 上午10:20:20
 */
public class WeekDaysUtil {
	
	//用来保存所有法定假日[元旦、五一、国庆]
	public static String[] statutoryHoliday = {"0101", "0102", "0103", "0501", "0502", "0503", "1001", "1002", "1003", "1004", "1005", "1006", "1007"};
	
	public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

	public static void main(String[] args) throws ParseException {
/*		List<String> hs = getHolidaysAndWeekends(2015);
		for(String y : hs){
			System.out.println(y);
		}
		String xd = "20150815";
		System.out.println(validate(xd, hs));
		
		String xx = "2015-08-15";
		System.out.println(xx.substring(0, 4));*/
	}

	public static List<String> getHolidaysAndWeekends(int year) {
		List<String> weekenDays = getWeekends(year);//拿到年度所有周末
		addStatutoryHolidays(year, weekenDays);//增加法定假日
		return weekenDays;
	}
	
	//返回指定日期前2个工作日
	public static String[] getTwoDaysAhead(String theDay, List<String> weekenDays) throws ParseException {
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(theDay));
		
		String[] twoDaysAhead = new String[2];
		
		int count = 0;
		while(count < 2){
			cal.add(Calendar.DATE, -1);
			boolean isHoliday = validate(sdf.format(cal.getTime()), weekenDays);
			
			if(!isHoliday){
				twoDaysAhead[count++] = sdf.format(cal.getTime());
			}
		}
		
		return twoDaysAhead;
	}

	public static boolean validate(String string, List<String> holidays) {
		//String mmdd = string.substring(4);

		for(String holiday: holidays){
			if(string.equals(holiday)){
				return true;
			}
		}
		
		return false;
	}

	public static void addStatutoryHolidays(int year, List<String> weekenDays) {
		for(String holiday: statutoryHoliday){
			weekenDays.add(year + holiday);
		}
	}

	public static List<String> getWeekends(int year){
		List<String> list = new ArrayList<String>();
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		
		Calendar cal = Calendar.getInstance(Locale.CHINA);
		cal.set(year, 0, 1);

		for(int day = 1; day <= cal.getActualMaximum(Calendar.DAY_OF_YEAR); day++){
			cal.set(Calendar.DAY_OF_YEAR, day);
			
			int weekDay = cal.get(Calendar.DAY_OF_WEEK);
			if(weekDay == Calendar.SATURDAY || weekDay == Calendar.SUNDAY){
				list.add(sdf.format(cal.getTime()));
			}
		}
		
		return list;
	}
}
